package com.example.sonone.xianliusuanfa;

public class TokenBucket {

    public long timeStamp = System.currentTimeMillis(); // 当前时间
    public long capacity = 100; // 桶的容量
    public long rate = 1; // 令牌放入速度
    public long tokens = 33; // 当前令牌数量

    public boolean grant() {
        long now = System.currentTimeMillis();
        // 先添加令牌
        tokens = Math.min(capacity, tokens + (now - timeStamp) * rate);
        timeStamp = now;
        if (tokens < 1) {
            // 若不到1个令牌,则拒绝
            return false;
        } else {
            // 还有令牌，领取令牌
            tokens -= 1;
            return true;
        }
    }

    public static void main(String[] args) {
        TokenBucket t = new TokenBucket();
        for (; ; ) {
            long now = System.currentTimeMillis();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    boolean grant = t.grant();
                    System.out.println(grant);
                }
            }).start();
            long end = System.currentTimeMillis();
            if (end - now > 3000) {
                return;
            }
        }
    }

}
